package org.jeecg.modules.clue.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Result;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.clue.entity.ClueTagAreaConfig;
import org.jeecg.modules.clue.entity.ClueUserTagAreaRelate;
import org.jeecg.modules.clue.entity.ClueUserTpCarRelate;
import org.jeecg.modules.clue.mapper.ClueUserTagAreaRelateMapper;
import org.jeecg.modules.clue.req.ClueUserTagAreaReq;
import org.jeecg.modules.clue.service.IClueTagAreaConfigService;
import org.jeecg.modules.clue.service.IClueUserTagAreaRelateService;
import org.jeecg.modules.clue.vo.ClueUserTagAreaVo;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.util.SecurityUtil;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @Description: 用户标签地区关联
 * @Author: jeecg-boot
 * @Date:   2025-01-05
 * @Version: V1.0
 */
@Service
@Slf4j
public class ClueUserTagAreaRelateServiceImpl extends ServiceImpl<ClueUserTagAreaRelateMapper, ClueUserTagAreaRelate> implements IClueUserTagAreaRelateService {
    @Resource
    IClueTagAreaConfigService clueTagAreaConfigService;
    @Resource
    ISysUserService sysUserService;
    @Override
    public List<ClueUserTagAreaVo> userList(String userId) {

        // 用户地区关联表
        List<ClueUserTagAreaRelate> userTagAreaRelates = list(new LambdaQueryWrapper<ClueUserTagAreaRelate>().eq(ClueUserTagAreaRelate::getUserId, userId));
        // 获取可用标签
        List<ClueTagAreaConfig> list = clueTagAreaConfigService.list(new LambdaQueryWrapper<ClueTagAreaConfig>().eq(ClueTagAreaConfig::getStatus, "Y").orderByAsc(ClueTagAreaConfig::getSort));
        return list.parallelStream().map(new Function<ClueTagAreaConfig, ClueUserTagAreaVo>() {
            @Override
            public ClueUserTagAreaVo apply(ClueTagAreaConfig clueTagAreaConfig) {
                ClueUserTagAreaVo vo = BeanUtil.toBean(clueTagAreaConfig, ClueUserTagAreaVo.class);
                vo.setTagAreaConfigId(clueTagAreaConfig.getId());

                // 设置当前
                List<ClueUserTagAreaRelate> areaRelateList = userTagAreaRelates.stream().filter(clueUserTagAreaRelate -> clueTagAreaConfig.getId().equals(clueUserTagAreaRelate.getTagAreaId())).collect(Collectors.toList());
                vo.setUserId(userId);

                 if (!areaRelateList.isEmpty()) {
                    ClueUserTagAreaRelate areaRelate = areaRelateList.get(0);
                    vo.setUserTagAreaId(areaRelate.getTagAreaId());
                    if (StringUtils.isNotBlank(areaRelate.getCityList())) {
                        vo.setUserCityList(areaRelate.getCityList());
                    }
                    vo.setConfigStatus(areaRelate.getStatus());

                }
                return vo;
            }
        }).collect(Collectors.toList());

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchSet(List<ClueUserTagAreaReq> clueUserTagAreaReqList) {
        log.info("batchSet {}", clueUserTagAreaReqList);

        List<ClueUserTagAreaRelate> areaRelateList = clueUserTagAreaReqList.parallelStream().filter(ClueUserTagAreaReq::getTagChecked)
                .map(clueUserTagAreaReq -> {
                    ClueUserTagAreaRelate areaRelate = new ClueUserTagAreaRelate();
                    areaRelate.setUserId(clueUserTagAreaReq.getUserId());
                    areaRelate.setTagAreaId(clueUserTagAreaReq.getTagAreaConfigId());
                     areaRelate.setCityList(clueUserTagAreaReq.getUserCityList());
                    return areaRelate;
                }).collect(Collectors.toList());

        // 先删除
        remove(new LambdaQueryWrapper<ClueUserTagAreaRelate>().eq(ClueUserTagAreaRelate::getUserId, clueUserTagAreaReqList.get(0).getUserId()));
        // 新增
        saveBatch(areaRelateList);


    }

    @Override
    public List<String> getTagImgBySourceAndCity(String source, String city) {
        SysUser sysUser = sysUserService.getUserByName(source);
        if (null == sysUser) {
            throw new RuntimeException("此渠道不存在："+source);
        }
        List<ClueUserTagAreaRelate> areaRelateList = list(new LambdaQueryWrapper<ClueUserTagAreaRelate>().eq(ClueUserTagAreaRelate::getUserId, sysUser.getId()));
        List<ClueUserTagAreaRelate> areaRelates = areaRelateList.parallelStream().filter(new Predicate<ClueUserTagAreaRelate>() {
            @Override
            public boolean test(ClueUserTagAreaRelate clueUserTagAreaRelate) {
                return StringUtils.isBlank(clueUserTagAreaRelate.getCityList()) ||

                        Arrays.asList(Optional.ofNullable(clueUserTagAreaRelate.getCityList()).orElse("").split(",")).contains(city);
            }
        }).collect(Collectors.toList());

        List<String> areaTagIds = areaRelates.parallelStream().map(ClueUserTagAreaRelate::getTagAreaId).collect(Collectors.toList());
        if (areaRelates.isEmpty()) {
            return Collections.emptyList();
        }
        List<String> imgList = clueTagAreaConfigService.list(new LambdaQueryWrapper<ClueTagAreaConfig>().in(ClueTagAreaConfig::getId, areaTagIds)).parallelStream()
                .map(ClueTagAreaConfig::getLogo)
                .filter(StringUtils::isNotBlank).collect(Collectors.toList());
        return imgList;
    }
}
